﻿using Core.Framework;
using DotNetty.Codecs.Http.WebSockets;
using DotNetty.Transport.Channels;
using System;
using System.Text;

namespace DotNetty.Framework
{
    /// <summary>
    /// 二进制数据处理类
    /// </summary>
    public class BinaryWebSocketFrameHandler<TMessage> : SimpleChannelInboundHandler<BinaryWebSocketFrame>
        where TMessage : AbstractMessage
    {

        IWebSocketEventTriggered<TMessage> eventTriggered;

        public BinaryWebSocketFrameHandler(
            IWebSocketEventTriggered<TMessage> eventTriggered
            )
        {
            this.eventTriggered = eventTriggered;
        }

        protected async override void ChannelRead0(IChannelHandlerContext ctx, BinaryWebSocketFrame binary)
        {

            if (Common.IsShutdowned)
            {
                return;
            }

            // 消息内容
            byte[] req = new byte[binary.Content.ReadableBytes];
            binary.Content.ReadBytes(req);
            var messageOfString = Encoding.UTF8.GetString(req);

            try
            {
                if (messageOfString != "h")
                {
                    // 是否是心跳
                    if (!string.IsNullOrWhiteSpace(messageOfString) & messageOfString?.Length > 1)
                    {
                        // 消息实体
                        var message = Newtonsoft.Json.JsonConvert.DeserializeObject<TMessage>(messageOfString);
                        await this.eventTriggered.OnMessage(ctx, message);
                    }
                }
            }
            catch (System.Exception ex)
            {
                await this.eventTriggered.OnError(ctx, new OnExceptionContext
                {
                    Action = "BinaryWebSocketFrameHandler.ChannelRead0",
                    Exception = ex,
                    Message = messageOfString
                });
            }
            finally
            {
                //if (binary.ReferenceCount > 0)
                //{
                //    binary.Release();
                //}
            }

        }
    }
}
